package com.AdvancedDemos.LearnVariousAPI.字符串生成类;

import java.util.Scanner;

public class LearnStringBuilderAndStringBuffer {
    public static void main(String[] args) {
        /**
         * StringBuilder代表可变字符串对象,相当于一个容器,它里面装的字符串是可以改变的,专门用于操作字符串
         * 与String类相比更适合做字符串的修改操作,效率更高,代码更简洁
         */

        //使用有参无参构造函数
        StringBuilder sb = new StringBuilder();//""
        StringBuilder sb1 = new StringBuilder("ITHEIMA");//"ITHEIMA"

        //1.在字符串末尾附加(拼接)
        System.out.println("----------------");
        sb.append(12);
        sb.append("HeiMa");
        sb.append('-');
        sb.append(false);
        //append支持链式编程,即append中除了把指定内容附加到字符串,还会返回调用的对象自身,于是便可以再次.append(...)
        sb.append('H').append('e').append('l').append('l').append('o');

        System.out.println(sb);//StringBuilder内部重写了toString函数,print时自动调用toString

        //2.将字符串反转
        System.out.println("----------------");
        sb = sb.reverse();
        System.out.println(sb);

        //3.返回字符串长度
        System.out.println("----------------");
        System.out.println("sb.length() = " + sb.length());

        //4.将StringBuilder转换成String
        System.out.println("----------------");
        System.out.println(sb.toString());


        /**
         * StringBuilder的好处,与String进行对比
         */
        sb.delete(0, sb.length());//先使用delete清空已添加字符串
        sb.setLength(0);//或者设置长度为0来清空已添加内容
        //或者重新new StringBuilder()
        //性能上 delete>setLength>new StringBuilder
        System.out.println("*" + sb.toString() + "*");

        String rs = "";
        for (int i = 0; i < 100000; i++) {
            rs += "wtp";
        }
        System.out.println(rs);

        Scanner sc = new Scanner(System.in);
        sc.next();
        System.out.println("--------------");

        for (int i = 0; i < 100000; i++) {
            sb.append("wtp");
        }
        System.out.println(sb.toString());

//        频繁的添加修改字符串建议使用StringBuilder


        /**
         * StringBuffer与StringBuilder用法完全一样,但是StringBuilder是线程(多用户同时使用时是)不安全的,StringBuffer是线程安全的
         */

        StringBuffer sb2 = new StringBuffer("I'm so stupid!");
        sb2.append(123);
        System.out.println(sb2);
    }
}


